import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [{
        path: '/',
        name: 'Home',
        redirect: "/index"
    },
    {
        path: '/index',
        component: () =>
            import ( /* webpackChunkName: "about" */ '@/views/index.vue'),
        children:[
            {
                path: '',
                name: 'Default',
                component: () =>
                    import ( /* webpackChunkName: "about" */ '@/views/sys/user/index.vue')
            },
            {
                path: '/sys/user',
                name: 'User',
                component: () =>
                    import ( /* webpackChunkName: "about" */ '@/views/sys/user/index.vue')
            },
            {
                path: '/sys/role',
                name: 'Role',
                component: () =>
                    import ( /* webpackChunkName: "about" */ '@/views/sys/role/index.vue')
            },
            {
                path: '/chapter/chapter',
                name: 'Chapter',
                component: () =>
                    import ( /* webpackChunkName: "about" */ '@/views/chapter/index.vue')
            },

        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () =>
            import ( /* webpackChunkName: "about" */ '@/components/login/index.vue')
    },

]
  // 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
  const originalPush = VueRouter.prototype.push
  VueRouter.prototype.push = function push (location) {
    return originalPush.call(this, location).catch(err => err)
  }

const router = new VueRouter({
    routes
})
// 路由拦截器
router.beforeEach(async (to, from, next) => {
    if(to.path == "/login"){
        next()
    }else{
        let token = localStorage.getItem('token');
        if (token) { // 获取当前的 token 是否存在
          next()
        } else {
          // 不存在 token，需要重新认证
          next({
            path: '/login',
            query: {
              redirect: to.fullPath
            }
          })
        }
    }

    // if (to.matched.some(record => record.meta.auth) && to.meta.auth) { // 判断该路由是否需要登录权限
    //   let token = localStorage.getItem('token');
    //   if (token) { // 获取当前的 token 是否存在
    //     next()
    //   } else {
    //     // 不存在 token，需要重新认证
    //     next({
    //       path: '/login',
    //       query: {
    //         redirect: to.fullPath
    //       }
    //     })
    //   }
    // }
    // next();
  });



export default router